/**
* 系统管理 用户管理
*/
<template>


  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>任务管理</el-breadcrumb-item>
    </el-breadcrumb>

    <div style="padding:5px;color:#000000;text-align: center;font-family:PingFang SC;font-size:30px">任务列表</div>
    <!-- 搜索筛选 -->
    <el-form :inline="true" :model="formInline" class="user-search">
      <el-form-item label="">
        <el-input size="small" @keyup.enter="getSearchPage"  v-model="formInline.taskName" placeholder="输入任务名称"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="getSearchPage">搜索</el-button>
        <el-button size="small" type="info" icon="el-icon-refresh" @click="reset">重置</el-button>
        <el-button size="small" type="success" icon="el-icon-plus" @click="handleEdit()">新增任务</el-button>
        <!--        <el-button size="small" type="primary" @click="handleunit()">部门设置</el-button>-->
      </el-form-item>
    </el-form>
    <!--列表-->
    <el-table size="small" @selection-change="selectChange" :data="taskData" highlight-current-row v-loading="loading" border element-loading-text="执行任务中" style="width: 100%;">
      <el-table-column v-if="false" align="center" type="selection" width="40">
      </el-table-column>
      <el-table-column align="center" sortable prop="id" v-if="false" label="序号" width="80">
      </el-table-column>
      <el-table-column align="center" sortable prop="sourceType" label="数据源类型" width="150">
      </el-table-column>


      <el-table-column align="center" prop="datasourceIds" label="数据源ID" width="80">
        <template  slot-scope="scope">
          <div class="sub-body" @click="showData(scope.row.id,scope.row.sourceType)">{{ scope.row.datasourceIds }}</div>
        </template>

      </el-table-column>


      <!--<el-table-column align="center" prop="datasourceIds" label="数据源ID" width="80">
        <template slot-scope="scope">

          <el-popover @show="getFileName(scope.row.id)" trigger="click" visible-arrow="false">
            <div slot="reference" >
              &lt;!&ndash; 问题列显示文本 即触发Popover显示的HTML元素 &ndash;&gt;
              <p class="text">{{scope.row.datasourceIds}}</p>
            </div>

            &lt;!&ndash; popover弹出框开始 &ndash;&gt;
            <el-table
              :data = "fileInfo"
              size="small"
              highlight-current-row
              border>
              <el-table-column align="center"  label="数据源ID" width="100">
                <template slot-scope="scope">
                <span v-for="(item, index) in fileInfo" :key="index">
                {{item.sourceId}}
                </span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="pdf名称" width="300">
                <template slot-scope="scope">
                <span  v-for="(item, index) in fileInfo" :key="index">
                {{item.fileName}}
                </span>
                </template>
              </el-table-column>
            </el-table>
            &lt;!&ndash; popover弹出框结束 &ndash;&gt;
          </el-popover>
        </template>
      </el-table-column>
-->



      <el-table-column align="center" prop="taskName" label="任务名称" width="120">
      </el-table-column>
      <el-table-column align="center" prop="example" label="条件" width="200">
      </el-table-column>
      <el-table-column align="center" sortable prop="status" label="状态" min-width="60">
      </el-table-column>

      <el-table-column align="center" v-if="false" sortable prop="createTime" label="创建时间" width="120">
      </el-table-column>
      <el-table-column align="center" v-if="false"  sortable prop="updateTime" label="修改时间" min-width="120">
      </el-table-column>
      <!-- 操作 -->
      <el-table-column align="center" label="操作" min-width="300">
        <template slot-scope="scope">
          <el-button size="mini" type="primary"@click="actionNow(scope.row.id,scope.row.status)">立即执行</el-button>
          <el-button size="mini" type="danger" @click="deleteTask(scope.row.id)">删除</el-button>
          <el-button size="mini" type="success" @click="getRes(scope.row.id,scope.row.status,scope.row.sourceType)">查看结果</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination v-bind:child-msg="pageparm" @callFather="callFather"></Pagination>
    <!-- 编辑界面 -->
    <el-dialog :title="title" :visible.sync="editFormVisible" width="50%" @click='closeDialog("edit")'>
      <el-form label-width="100px" ref="editForm" :model="editForm" :rules="rules">

        <el-form-item label="任务名称" prop="taskName">
          <el-input size="mini" v-model="editForm.taskName" auto-complete="off" placeholder="请输入任务名称"></el-input>
        </el-form-item>



        <el-form-item label="数据源类型" prop="sourceType">
          <el-select size="small" v-model="editForm.sourceType" auto-complete="off"placeholder="请选择数据源类型" class="userRole"@change="lossFocus">
            <el-option label="结构化数据源" value="结构化数据源"></el-option>
            <el-option label="非结构化数据源" value="非结构化数据源" @click.native="openDialog"></el-option>
          </el-select>
        </el-form-item>

        <!--非结构化数据源-->
        <el-form-item v-show="isShow"  label="文件类型">
          <el-table
            v-model="editForm.datasourceIds"
            :data="checkedData"
            size="small"
            highlight-current-row
            border>
            <el-table-column v-if="false"  prop="id" label="数据源ID"/>
            <el-table-column prop="tag" label="文件类别"/>
            <el-table-column prop="fileName" label="pdf名称"/>
          </el-table>
         <!-- <el-button size="small" type="success" icon="el-icon-plus" @click.native="openDialog">重新添加</el-button>
        --></el-form-item>

        <!--选择结构化数据源-->
        <el-form-item v-show="isShow1"  label="数据源表" prop="datasourceIds">
          <el-select v-model="editForm.datasourceIds" multiple class="filter-item" placeholder="请选择数据源表" >
            <el-option v-for="data in StructSourceData" :key="data.id" :label="data.dataTable" :value="data.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="执行条件" prop="example">
          <el-select size="mini" v-model="editForm.example" placeholder="请选择执行条件">
            <el-option
              v-for="item in exampleData"
              :key="item.id"
              :label="item.example"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>




      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click='closeDialog("edit")'>取消</el-button>
        <el-button size="small" type="primary" :loading="loading" class="title" @click="submitForm('editForm')">保存</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :visible.sync="dialogVisible"
      title="选择非结构化数据"
      fullscreen
      :show-close="false">

      <un-struct-data-man ref="page"/>

      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="onConfirm">确 定</el-button>
      </span>
    </el-dialog>

    <!--非结构化数据源信息-->
    <el-dialog title="非结构化数据源信息" :visible.sync="showDataDetail" width="36%" @click='closeDialog("edit")'>

      <el-table
        :data="fileInfo"
        size="small"
        highlight-current-row
        border>
        <el-table-column align="center"  prop ="sourceId" label="数据源ID" width="100">
         <!-- <template slot-scope="scope">
            <span v-for="(item, index) in scope.row.sourceId" :key="index">{{item}}</span>
          </template>-->
        </el-table-column>
        <el-table-column align="center" prop ="FileName" label="pdf名称" width="300">
          <!--<template slot-scope="scope">
            <span v-for="(item, index) in scope.row.FileName" :key="index">{{item}}</span>
          </template>-->
        </el-table-column>
      </el-table>

    </el-dialog>

    <!--结构化数据源信息-->
    <el-dialog title="结构化数据源信息" :visible.sync="showStructDataDetail" width="51%" @click='closeDialog("edit")'>

      <el-table
        :data="structInfo"
        size="small"
        highlight-current-row
        border>
        <el-table-column align="center" sortable prop="id" label="数据源ID" width="110">
        </el-table-column>
        <el-table-column align="center" prop="dataTable" label="数据源名称" width="150">
        </el-table-column>
        <el-table-column align="center" prop="datastore" label="数据源" width="114">
        </el-table-column>

        <el-table-column align="center" prop="url" label="IP" width="100">
        </el-table-column>
        <el-table-column align="center" prop="fileds" label="字段" width="110">
        </el-table-column>

      </el-table>

    </el-dialog>

  </div>
</template>

<script>
  // 导入请求方法

  import Pagination from '../../components/Pagination'
  import axios from "axios";

  import UnStructDataMan from "../dataManage/UnStructDataMan.vue";
  export default {
    data() {
      return {

        tagData:[],
        fileData:[],
        isShow:false,
        isShow1:false,

        loading: false, //是显示加载
        title: '新增任务',
        editFormVisible: false, //控制编辑页面显示与隐藏

        showDataDetail:false, // 控制非结构化数据源信息展示页面
        showStructDataDetail:false,// 控制结构化数据源信息展示页面
        souId:[],
        fileName:[],

        // 编辑与添加
        editForm: {
          id: '',
          taskName: '',
          modeltargets:[],
          example: '',
          sourceType: '',
          sourceId: '',
          datasourceIds:[],
          tagId:'' ,
          status:'未执行',
          userId: localStorage.getItem('userId')
        },
        // 选择数据
        selectdata: [],
        // rules表单验证
        rules: {
          taskName: [
            { required: true, message: '请输入任务名称', trigger: 'blur' }
          ],
          sourceType: [{ required: true, message: '请选择数据源类型', trigger: 'blur' }],
          datasourceIds: [{ required: true, message: '请选择数据源表', trigger: 'blur' }],
          example: [{ required: true, message: '请选择执行条件', trigger: 'blur' }],


        },

        // 请求数据参数
        formInline: {
          page: 1,
          limit: 10,
          taskName: '',
          isLock: ''
        },

        //任务数据
        taskData: [],
        // 非结构化数据源信息
        UnStructSourceData:[],
        //结构化数据源信息
        StructSourceData :[],
        // 条件数据
        exampleData:[],
        ResponseData:[],
        SourceDataId:[],
        // 分页参数

        //文件名列表
        UnStructSourceDataFileName:[],
        fileInfo:[{sourceId:[],FileName:[]}],
        structInfo:[],
        Data:[],
        pageparm: {
          currentPage: 1,
          pageSize: 10,
          total: 10
        },

        dialogVisible: false,
        checkedData: []
      }
    },
    // 注册组件
    components: {
      Pagination,
      UnStructDataMan
    },

    /**
     * 数据发生改变
     */
    watch: {},

    /**
     * 创建完毕
     */
    created() {
      this.data1 = localStorage.getItem('userId')
      this.getSearchPage()
    },

    /**
     * 里面的方法只有被调用才会执行
     */
    methods: {

      changeTag(){
        this.fileData = []
        //
        for(var i = 0; i < this.UnStructSourceData.length; i++){
          if(this.UnStructSourceData[i].tagId == this.editForm.tagId){
            this.fileData[this.fileData.length] = {id:this.UnStructSourceData[i].id, fileName:this.UnStructSourceData[i].fileName}
          }
        }
      },
      // 获取任务数据
      getSearchPage(formInline) {
        this.logining = true
        let url = this.$global.javaUrl +"/task/list"
        let config = {
          headers:
            {
              //'Content-Type':'application/json',
              'user' : localStorage.getItem('userId')
            },
          params: {
            taskName:this.formInline.taskName,
            pageNum: this.formInline.page,
            pageSize:this.formInline.limit,

          }
        }

        axios.get(url, config).then(response=>{
          this.taskData = response.data.data.rows

          this.pageparm.total = response.data.data.records
          for(var i=0;i<this.taskData.length;i++) {

            this.UnStructSourceDataFileName[i] = {
              id: this.taskData[i].id,
              sourceIds: this.taskData[i].sourceIds,
              fileNames: this.taskData[i].fileNames
            }

          }




         })

        this.getUnStructSourceData()
        this.getEaxmple()
        this.getStructSource()



      },
      //展示非结构化数据源信息
      showData(id,type){
        if(type=='非结构化数据源'){
          this.fileInfo = []
          this.souId =[]
          this.showDataDetail = true
          for(let i = 0; i < this.UnStructSourceDataFileName.length; i++) {
            if(this.UnStructSourceDataFileName[i].id == id){

              this.souId = this.UnStructSourceDataFileName[i].sourceIds;
              this.fileName = this.UnStructSourceDataFileName[i].fileNames;

              for (let i = 0; i < this.souId.length; i++) {
                this.fileInfo[i] = {sourceId: this.souId[i], FileName: this.fileName[i]}
                console.log("1" + this.fileInfo[i].sourceId)
                console.log("1" + this.fileInfo[i].FileName)
              }
            }
          }

        }else{
          this.showStructDataDetail = true
          this.structInfo = []
          this.souId = []
          for(let i = 0; i < this.UnStructSourceDataFileName.length; i++){
            if(this.UnStructSourceDataFileName[i].id == id){
              this.souId = this.UnStructSourceDataFileName[i].sourceIds;
              for (let j = 0; j < this.souId.length; j++) {
                for(let x = 0;x < this.StructSourceData.length;x++){
                  if(this.souId[j] === this.StructSourceData[x].id){
                    this.structInfo[x] = this.StructSourceData[x]
                    console.log("结构"+this.StructSourceData[x])
                  }

                }
              }
            }
          }
        }
      },
      // 获取结构化数据源信息
      getStructSource() {

        //登录
        let url = this.$global.javaUrl + "/dataSource/list"
        axios.get(url,{
          headers:
            {
              'user' : localStorage.getItem('userId')
            },
          params:
            {
              pageNum: '1',
              pageSize:10
            }
        }).then(res=>{

          console.log("返回信息")
          console.log(res)
          this.StructSourceData = res.data.data.rows
          this.SourceDataId = res.data.data.rows.datasourceIds
          console.log("hhh"+this.StructSourceData)
        })
      },


      getUnStructSourceData(){
        this.logining = true
        let url = this.$global.javaUrl+"/dataSource/listUnStruct"
        let config = {
          headers:
            {
              //'Content-Type':'application/json',
              'user' : localStorage.getItem('userId')
            },
          params: {
            pageNum: '1',
            pageSize:'20',
            tagId:0
            //isLock: this.formInline.isLock
          }
        }

        axios.get(url, config).then(response=>{
          this.UnStructSourceData = response.data.data.rows



          var ll = [];
          var i = 0;
          for(i = 0; i < this.UnStructSourceData.length; i++){
            if(!ll.includes(this.UnStructSourceData[i].tag)){
              ll[ll.length] = this.UnStructSourceData[i].tag
              this.tagData[this.tagData.length] = {id:this.UnStructSourceData[i].tagId,tag:this.UnStructSourceData[i].tag}
            }
          }

        })


      },
      // 获取执行条件
      getEaxmple() {
        this.logining = true
        let url = this.$global.javaUrl+"/target/list"
        let config = {
          headers:
            {
              //'Content-Type':'application/json',
              'user' : localStorage.getItem('userId')
            },
          params:
            {
              name:this.formInline.taskName,
              tag:'条件',
              pageNum: '1',
              pageSize:'100',

            }
        }
        axios.get(url, config).then(response=>{
          this.exampleData = response.data.data.rows


        })



      },

      lossFocus(){
        if(this.editForm.sourceType === "结构化数据源"){
          this.isShow1 = true
          this.isShow = false
        }else{
          console.log("tagData",this.tagData)
          this.isShow = true
          this.isShow1 = false
        }
        console.log(this.editForm)
        if(this.editForm.taskName != undefined
          &&this.editForm.example!=undefined
          &&this.editForm.sourceType!=undefined
          &&this.editForm.sourceId!=undefined){//条件满足，获取table信息
          console.log("满足条件---")
          let url = this.$global.javaUrl+"/target/list"
          let config = {
            headers: {
              'Content-Type': 'multipart/form-data',
              'user' : localStorage.getItem('userId')
            }
          }
          axios.get(url,{   // 这个请求好像并没有什么用
            headers:
              {
                'user' : localStorage.getItem('userId')
              },
            params:
              {
                name:this.editForm.taskName,
                pageNum: '1',
                pageSize:'10',
              }
          }).then(res=>{
            if(res.status == 200){
              console.log("返回信息")
              console.log(res.data.data.rows)
              var list_data = res.data.data.rows
              this.Tableoptions = []
              for(var i = 0; i < list_data.length; i++){
                this.Tableoptions[i] = {label:list_data[i],value:list_data[i]}
              }
            }else{

            }
          }).catch(err=>{
            this.$message.error('链接信息不正确')
          })

        }
      },

      // 立即执行
      actionNow(id,status) {
        this.logining = true
       if(status == "已执行"){
         this.$message({
           type: 'warning',
           message: "任务已执行，请勿重复操作！"
         })
       }else{
         let url = this.$global.javaUrl+"/task/actionNow"
         let config = {
           headers:
             {
               //'Content-Type':'application/json',
               'user' : localStorage.getItem('userId')
             },
           params:{'taskId':id}

         }

         const loading = this.$loading({
           lock: true,
           text: '任务执行中',
           spinner: 'el-icon-loading',
           background: 'rgba(0, 0, 0, 0.7)'
         });

         axios.get(url,config).then(response=>{
           this.ResponseData = response.data.data.rows

           if (response.data.code == 200) {
             this.$message({
               type: 'success',
               message: "任务执行完成，可查看结果！"
             })
             this.getSearchPage()
           } else {
             this.$message({
               type: 'info',
               message: response.msg
             })
           }

         }).finally(() => {
           loading.close()
         })

       }


      },
      // 分页插件事件
      callFather(parm) {
        this.formInline.page = parm.currentPage
        this.formInline.limit = parm.pageSize
        this.getSearchPage()
      },

      //显示编辑界面
      handleEdit: function(index, row) {
        this.editFormVisible = true
        if (row != undefined && row != 'undefined') {
          this.title = '修改任务'
          this.editForm.id = row.id

        } else {
          this.isShow = false
          this.isShow1 = false
          this.title = '新增任务'
          this.editForm.id = ''
          this.editForm.taskName = ''
          this.editForm.example = ''
          this.editForm.sourceType = ''
          this.editForm.sourceId = ''
          this.editForm.datasourceIds =''
        }
      },
      // 编辑、添加提交方法
      submitForm(editData) {
        var cur_id = this.editForm.example;
        var cur_e = "";
        this.editForm.modelTargets = []
        for(var i = 0; i < this.exampleData.length; i++){
          if(this.exampleData[i].id == this.editForm.example){
            cur_e = this.exampleData[i].example
          }
        }
        this.editForm.modelTargets[0] = {
          id:cur_id,
          example:cur_e
        }
        if(this.editForm.sourceType == "非结构化数据源"){
          this.editForm.datasourceIds = []
          for(var i =0;i<this.checkedData.length;i++){
            this.editForm.datasourceIds[i]= this.checkedData[i]["id"]
          }
        }
        console.log("this.editForm.datasourceIds",this.editForm.datasourceIds)
        let config = {
          headers:
            {
              'Content-Type':'application/json',
              'user' : localStorage.getItem('userId')
            }
        }
        this.$refs[editData].validate(valid => {
          if (valid) {
            console.log("fffffffffff",this.editForm)
            // 请求方法
            axios
              .post(this.$global.javaUrl+"/task/saveOrUpdate",this.editForm,config)
              .then(res => {
                this.editFormVisible = false
                this.loading = false
                if (res.data.data != null) {
                  this.$message({
                    type: 'success',
                    message: "数据保存成功！"
                  })
                  this.getSearchPage()
                } else {
                  this.$message({
                    type: 'info',
                    message: res.msg
                  })
                }
              })
              .catch(err => {
                this.editFormVisible = false
                this.loading = false
                this.$message.error('保存失败，请稍后再试！')
              })
          } else {
            return false
          }
        })

      },


      // 选择复选框事件
      selectChange(val) {
        this.selectdata = val
      },
      // 关闭编辑、增加弹出框
      closeDialog(dialog) {
        if (dialog == 'edit') {
          this.isShow1 = false
          this.isShow = false
          this.showDataDetail = false
          this.showStructDataDetail = false
          this.editFormVisible = false

        } else if (dialog == 'perm') {
          this.dataAccessshow = false
        } else if (dialog == 'unit') {
          this.unitAccessshow = false
        }
      },


      // 删除任务
      deleteTask(id) {
        let config = {
          headers:
            {
              'Content-Type':'application/json',
              'user' : localStorage.getItem('userId')
            },
          params:{'taskId':id}

        }

        this.$confirm('确定要删除吗?', '信息', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            // 删除
            axios.get(this.$global.javaUrl+"/task/delete",config)
              .then(res => {
                if (res.data.data !=null) {
                  this.$message({
                    type: 'success',
                    message: '数据已删除!'
                  })
                  this.getSearchPage()
                } else {
                  this.$message({
                    type: 'info',
                    message: "1111"
                  })
                }
              })
              .catch(err => {
                this.loading = false
                this.$message.error('数据删除失败，请稍后再试！')
              })
            this.getSearchPage()
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除！'
            })
          })
      },
      // 查看执行结果
      getRes(id,status,type){
        if(status=='已执行'){
          this.$router.push({path:'getResults',query:{id:id,sourceType:type}});
        }
        else{
          this.$message({
            type: 'info',
            message: '任务未执行，无法查看!'
          })
        }
      },
      //重置
      reset() {
        this.formInline.page = 1
        this.formInline.taskName = ""
        this.getSearchPage(this.formInline)
      },
      openDialog() {
        this.dialogVisible = true;
        this.$refs.page.clearSelection();

      },
      onConfirm() {
        const s = this.$refs.page.getSelection();

        if(s==0){

          this.$message({
            type: 'warning',
            message: "未选择数据,无法保存"
          })

        }else{
          this.dialogVisible = false;
          this.checkedData = s;

          console.log("11",this.checkedData)
        }

      },
      cancel(){
        this.editForm.sourceType = ''
        this.dialogVisible = false
        this.isShow = false
      }
    }
  }
</script>

<style scoped>
  .user-search {
    margin-top: 20px;
  }
  .userRole {
    width: 100%;
  }
</style>
